# -*- coding: utf-8 -*-
from gstreamer_lib.GStreamerWrapper import GStreamerWrapper
import cv2
import time
from datetime import datetime
import threading
import sys
import tty
import termios

# 全局变量用于控制录制循环
stop_recording = False

def keyboard_listener():
    """
    在后台线程中监听键盘输入，当按下 'q' 键时，设置停止标志。
    """
    global stop_recording
    # 获取标准输入的文件描述符
    fd = sys.stdin.fileno()
    # 保存终端旧的设置
    old_settings = termios.tcgetattr(fd)
    try:
        # 设置终端为非规范模式 (raw mode)，不进行行缓冲
        tty.setraw(sys.stdin.fileno())
        while not stop_recording:
            # 直接从标准输入读取一个字符
            char = sys.stdin.read(1)
            if char.lower() == 'q':
                stop_recording = True
                break
    finally:
        # 恢复终端的旧设置，确保终端在程序退出后正常
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

def main():
    global stop_recording
    frame_width = 1920
    frame_height = 1080
    print("Initializing GStreamerWrapper...")
    wrapper = GStreamerWrapper(width=frame_width, height=frame_height)

    # 视频录制参数，从 GStreamerWrapper 实例中获取分辨率
    fps = 30  # 视频帧率，根据 GStreamerWrapper 管道设置调整
    
    # 根据当前时间生成文件名，直接保存为 AVI 格式
    current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    output_file = f"video_{current_time}.avi"
    
    # 初始化视频写入器，使用 MJPG 编码器以获得更好的兼容性
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    out = cv2.VideoWriter(output_file, fourcc, fps, (frame_width, frame_height))
    
    if not out.isOpened():
        print("Error: VideoWriter failed to open. Cannot save video.")
        return

    print(f"Successfully configured to save AVI video.")

    # 启动键盘监听线程
    keyboard_thread = threading.Thread(target=keyboard_listener)
    keyboard_thread.daemon = True # 设置为守护线程，主线程退出时自动退出
    keyboard_thread.start()

    # 等待第一帧准备就绪
    print("Waiting for the first frame...")
    frame = None
    while frame is None:
        frame = wrapper.GetFrame()

    print("\n------------------------------")
    print("Recording started. Press 'q' to stop.")
    print("------------------------------")
    
    # 录制循环
    while not stop_recording:
        frame = wrapper.GetFrame()

        if frame is not None:
            # 创建一个可写的副本
            writable_frame = frame.copy()
            # 将帧写入视频文件
            out.write(writable_frame)
    
    # 录制结束后，设置停止标志以确保监听线程退出
    stop_recording = True

    # 释放资源
    out.release()
    print("\nRecording stopped by user.")
    print(f"Video saved to {output_file}")

    # 清理 GStreamer 管道和线程
    print("Stopping GStreamer thread...")
    wrapper.StopThread()
    print("Test complete.")

if __name__ == "__main__":
    main()
